"use strict";

const axios = require("axios");
const urlJoin = require("url-join");
const semver = require("semver");

async function getNpmInfo(npmName, registry) {
  if (!npmName) {
    return null;
  }

  const registryUrl = registry || getDefaultRegistry();
  const npmInfoUrl = urlJoin(registryUrl, npmName);
  const res = await axios.get(npmInfoUrl);
  if (res.status === 200) {
    return res.data;
  }
  return null;
}

async function getNpmVersions(npmName, registry) {
  const data = await getNpmInfo(npmName, registry);
  if (data) {
    return Object.keys(data.versions);
  } else {
    return [];
  }
}

function getSemverVersions(baseVersion, versions) {
  versions = versions
    .filter((version) => {
      return semver.satisfies(version, `^${baseVersion}`);
    })
    .sort((a, b) => {
      const flag = semver.gt(b, a);
      return flag ? 1 : -1;
    });
  return versions;
}

async function getNpmSemverVersions(baseVersion, npmName, registry) {
  const versions = await getNpmVersions(npmName, registry);
  const newVersions = getSemverVersions(baseVersion, versions);
  if (newVersions && newVersions.length > 0) {
    return newVersions[0];
  }
  return null;
}

async function getNpmLatestVersion(npmName, registry) {
  let versions = await getNpmVersions(npmName, registry);
  if (versions) {
    versions.sort((a, b) => {
      const flag = semver.gt(b, a);
      return flag ? 1 : -1;
    });
    return versions[0];
  }
  return null;
}

function getDefaultRegistry(isOriginal = true) {
  return isOriginal
    ? "https://registry.npmjs.org"
    : "https://registry.npm.taobao.org";
}

module.exports = {
  getNpmLatestVersion,
  getDefaultRegistry,
  getNpmInfo,
  getNpmVersions,
  getNpmSemverVersions,
};
